package com.ruoyi.wx.service;

import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.wx.config.WxMaConfiguration;
import com.ruoyi.wx.domain.WxMaForm;
import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import cn.hutool.core.collection.CollectionUtil;
import me.chanjar.weixin.common.bean.imgproc.WxImgProcQrCodeResult;
import me.chanjar.weixin.common.bean.imgproc.WxImgProcQrCodeResult.CodeResults;
import me.chanjar.weixin.common.service.WxImgProcService;

@Component
public class WxMaCodeService {

	/**
     * 生成二维码
     */
	public byte[] createQrCode(WxMaForm wxMaForm){
		// 设置小程序二维码线条颜色为黑色
        WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
        byte[] qrCodeBytes = null;
		try {
			WxMaService wxMaService = WxMaConfiguration.getMaServices().get(wxMaForm.getAppId());
			WxMaQrcodeService qrcodeService = wxMaService.getQrcodeService();
			qrCodeBytes = qrcodeService.createWxaCodeBytes(wxMaForm.getQrPath(), "release", 640, false, lineColor, false);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("生成二维码失败");
		}
		return qrCodeBytes;
	}
	
	/**
     * 解析二维码
     */
	public String getQrCode(WxMaForm wxMaForm){
		List<String> lockList  = new ArrayList<String>();
		try {
			String[] urls = wxMaForm.getUrl().split(",");
			for(String url : urls){
				WxMaService wxMaService = WxMaConfiguration.getMaServices().get(wxMaForm.getAppId());
				WxImgProcService imgProcService = wxMaService.getImgProcService();
				WxImgProcQrCodeResult result = imgProcService.qrCode(url);
				List<CodeResults> list = result.getCodeResults();
				if(list != null && list.size() > 0){
					String typeName = list.get(0).getTypeName();
					if("QR_CODE".equals(typeName)){
						lockList.add(url);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return CollectionUtil.join(lockList, ",");
	}
	
	/**
     * 生成二维码
     */
	public byte[] createQrCodeUnlimit(WxMaForm wxMaForm){
		// 设置小程序二维码线条颜色为黑色
        WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
        byte[] qrCodeBytes = null;
		try {
			WxMaService wxMaService = WxMaConfiguration.getMaServices().get(wxMaForm.getAppId());
			WxMaQrcodeService qrcodeService = wxMaService.getQrcodeService();
			qrCodeBytes = qrcodeService.createWxaCodeUnlimitBytes(wxMaForm.getScene(), wxMaForm.getQrPath(), true, "release", 640, false, lineColor, false);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ServiceException("生成二维码失败");
		}
		return qrCodeBytes;
	}
	
}
